package com.jfl.utils;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常工具类
 * 
 * @author 赵炎
 * @version [V1.00, 2018年12月3日]
 * @since V1.00
 */
public class ExceptionUtil
{
    
    /**
     * <一句话功能简述>
     * 
     * @param e
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static RuntimeException unchecked(Exception e)
    {
        if (e instanceof RuntimeException)
        {
            return (RuntimeException)e;
        }
        else
        {
            return new RuntimeException(e);
        }
    }
    
    /**
     * ErrorStack转化为String.
     * 
     * @param e
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String getStackTraceAsString(Throwable e)
    {
        if (e == null)
        {
            return "";
        }
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }
    
    /**
     * 判断异常是否由某些底层的异常引起
     * 
     * @param ex
     * @param causeExceptionClasses
     * @return
     * @see [类、类#方法、类#成员]
     */
    @SafeVarargs
    public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses)
    {
        Throwable cause = ex.getCause();
        while (cause != null)
        {
            for (Class<? extends Exception> causeClass : causeExceptionClasses)
            {
                if (causeClass.isInstance(cause))
                {
                    return true;
                }
            }
            cause = cause.getCause();
        }
        return false;
    }
    

    /** 
     * 在request中获取异常类
     * @param request
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static Throwable getThrowable(HttpServletRequest request)
    {
        Throwable ex = null;
        if (request.getAttribute("exception") != null)
        {
            ex = (Throwable)request.getAttribute("exception");
        }
        else if (request.getAttribute("javax.servlet.error.exception") != null)
        {
            ex = (Throwable)request.getAttribute("javax.servlet.error.exception");
        }
        return ex;
    }
    
}
